package com.study.handle;

import com.study.exception.ServiceException;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 返回结果统一处理类
 * @author ：ihao ∶）
 * @date ：Created in 2020-11-29 12:23
 */
@RestControllerAdvice
@Slf4j
public class GlobalResponseHandle implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//        Type genericParameterType = methodParameter.getGenericParameterType();
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }

    /**
     * ServiceException 异常处理
     * @date 2020/12/3 10:50
     */
    @ExceptionHandler(ServiceException.class)
    public Object exceptionHandler(HttpServletRequest request, ServiceException e){
        log.info("{} 请求参数：{} 请求失败：{} ",request.getRequestURI(), getParameter(request), e.getMessage());
        return Result.fail(e.getMessage(), e.getCode());
    }

    public String getParameter(HttpServletRequest request){
        StringBuilder sb = new StringBuilder();
        for(Map.Entry<String,String[]> param : request.getParameterMap().entrySet()){
            sb.append(param.getKey())
                    .append(" = ")
                    .append(String.join("", param.getValue()))
                    .append("   ");
        }
        return sb.toString();
    }



}
